<template>
  <div class="enroll-page">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true">
        <el-form-item label="关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索活动标题"
            clearable
            style="width: 240px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option label="未开始" :value="0">
              <span style="float: left">未开始</span>
              <el-tag type="success" size="small" style="float: right">待开始</el-tag>
            </el-option>
            <el-option label="进行中" :value="1">
              <span style="float: left">进行中</span>
              <el-tag type="warning" size="small" style="float: right">进行中</el-tag>
            </el-option>
            <el-option label="已结束" :value="2">
              <span style="float: left">已结束</span>
              <el-tag type="info" size="small" style="float: right">已结束</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <div class="activity-list">
      <el-row :gutter="20" v-loading="loading">
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          v-for="activity in activityList"
          :key="activity.id"
        >
          <el-card class="activity-card" shadow="hover">
            <!-- 活动图片 -->
            <div class="activity-image" @click="handleViewDetail(activity.id)">
              <el-image
                v-if="activity.images && activity.images.length > 0"
                :src="activity.images[0]"
                fit="cover"
                :preview-src-list="[]"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div v-else class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>

              <!-- 状态标签 -->
              <div class="status-tag">
                <el-tag v-if="activity.status === 0" type="success" size="small">未开始</el-tag>
                <el-tag v-else-if="activity.status === 1" type="warning" size="small">进行中</el-tag>
                <el-tag v-else type="info" size="small">已结束</el-tag>
              </div>
            </div>

            <!-- 活动信息 -->
            <div class="activity-info" @click="handleViewDetail(activity.id)">
              <h3 class="activity-title">{{ activity.title }}</h3>
              <p class="activity-desc">{{ activity.description }}</p>

              <div class="activity-meta">
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ activity.location }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDate(activity.startTime) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>
                    {{ activity.currentParticipants }}/{{ activity.maxParticipants === 0 ? '不限' : activity.maxParticipants }}
                  </span>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="activity-actions">
              <el-button type="primary" size="small" @click="handleViewDetail(activity.id)">
                查看详情
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click.stop="handleDelete(activity.id)"
                v-if="hasPermission('activity:delete')"
              >
                删除活动
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="!loading && activityList.length === 0" description="暂无活动" />
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :page-sizes="[8, 16, 24, 32]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 活动详情对话框 -->
    <ActivityDetailDialog
      v-model="detailVisible"
      :activity-id="currentActivityId"
      @refresh="getActivityList"
      @edit="handleEdit"
    />

    <!-- 编辑活动对话框 -->
    <EditActivityDialog
      v-model="editVisible"
      :activity-id="currentActivityId"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Location, Calendar, User, Search } from '@element-plus/icons-vue'
import { reqGetActivityList, reqDeleteActivity } from '@/api/activity'
import type { ActivityItem } from '@/api/activity/type'
import ActivityDetailDialog from './components/ActivityDetailDialog.vue'
import EditActivityDialog from './components/EditActivityDialog.vue'
import useUserStore from '@/stores/modules/user'
import dayjs from 'dayjs'

// 获取用户信息
const userStore = useUserStore()

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 8,
  keyword: '',
  status: undefined as number | undefined
})

// 活动列表
const activityList = ref<ActivityItem[]>([])
const total = ref(0)
const loading = ref(false)

// 详情对话框
const detailVisible = ref(false)
const currentActivityId = ref<number>(0)

// 编辑对话框
const editVisible = ref(false)

// 获取活动列表
const getActivityList = async () => {
  if (loading.value) return
  loading.value = true

  try {
    const result: any = await reqGetActivityList(queryParams)
    if (result.code === 200) {
      activityList.value = result.data.records || []
      total.value = result.data.total || 0
    } else {
      ElMessage.error(result.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getActivityList()
}

// 重置
const handleReset = () => {
  queryParams.keyword = ''
  queryParams.status = undefined
  queryParams.page = 1
  getActivityList()
}

// 分页处理
const handlePageChange = () => {
  getActivityList()
}

const handleSizeChange = () => {
  queryParams.page = 1
  getActivityList()
}

// 查看详情
const handleViewDetail = (id: number) => {
  currentActivityId.value = id
  detailVisible.value = true
}

// 编辑活动
const handleEdit = (id: number) => {
  currentActivityId.value = id
  editVisible.value = true
}

// 编辑成功
const handleEditSuccess = () => {
  getActivityList()
}

// 权限判断方法
const hasPermission = (perm: string) => {
  return userStore.buttons.includes(perm)
}


// 删除活动
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该活动吗？删除后将无法恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const result: any = await reqDeleteActivity(id)

    if (result.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页没有数据了，返回上一页
      if (activityList.value.length === 1 && queryParams.page > 1) {
        queryParams.page--
      }
      await getActivityList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  } finally {
    loading.value = false
  }
}

// 判断是否是活动发布者
const isPublisher = (publisherId: number) => {
  return userStore.userId === publisherId
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format('MM-DD HH:mm')
}

// 页面加载时获取列表
onMounted(() => {
  getActivityList()
})
</script>

<style scoped lang="scss">
.enroll-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.activity-list {
  min-height: 400px;
}

.activity-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.activity-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;

  .el-image {
    width: 100%;
    height: 100%;
  }

  .image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 40px;
  }

  .status-tag {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}

.activity-info {
  padding: 15px;

  .activity-title {
    margin: 0 0 10px;
    font-size: 16px;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .activity-desc {
    margin: 0 0 15px;
    font-size: 14px;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    min-height: 40px;
  }

  .activity-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 13px;
      color: #909399;

      .el-icon {
        font-size: 14px;
      }
    }
  }
}

.activity-actions {
  padding: 0 15px 15px;
  display: flex;
  gap: 10px;

  .el-button {
    flex: 1;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .enroll-page {
    padding: 10px;
  }

  .activity-image {
    height: 150px;
  }
}
</style>
